package com.yilife.hmstr.service.impl;

import com.yilife.hmstr.domain.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 解析检测报告html工具类
 * @author dede
 *
 */
@Service
public class HmstrParseUtil {
	
	/**
	 * 从本地读取html文件
	 * @return
	 */
	public static Document ReadFile(String filepath){
		//File file=new File("C:/Users/dede/Desktop/经络报告/新建文件夹/13602896904(经络分析).htm");
		//File file=new File("C:/Users/dede/Desktop/经络报告/新建文件夹/13602896904(检测报告).htm");
		//File file=new File("C:/Users/dede/Desktop/经络报告/新建文件夹/13602896904(经络表).htm");
		//File file=new File("C:/Users/dede/Desktop/经络报告/新建文件夹/13602896904(五行图).htm");
		File file=new File(filepath);
		Document document=null;
		try {
			document=Jsoup.parse(file, "gb2312");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return document;
	}
	
	/**
	 * 解析经络报告
	 * @param document
	 * @param hmstrId
	 * @return
	 */
	public static ma ParseMeridianAnalysis(Document document,Long hmstrId){
		List<MeridianAnalysis> mas=new ArrayList<MeridianAnalysis>();
		Elements zh=document.select("table tbody tr td");
		String symptomName="[\u4e00-\u9fa5].*在(?:虚|实)[\u4e00-\u9fa5].*";//正则表达式匹配症状名称
		String suggest="(?<=建议：).*";//正则表达式匹配建议
		String symptom="(?<=症状：).*";//正则表达式匹配症状
		List<String> symptomNames = new ArrayList<String>();
		List<String> suggests = new ArrayList<String>();
		List<String> symptoms = new ArrayList<String>();
		//字符串转换为对象
		
		for (Element element : zh) {
			
			Matcher matcher1=Pattern.compile(symptomName).matcher(element.text());
			Matcher matcher2=Pattern.compile(symptom).matcher(element.text());
			Matcher matcher3=Pattern.compile(suggest).matcher(element.text());
			if(matcher1.find()){
				symptomNames.add(matcher1.group());
			}else if(matcher2.find()){
				symptoms.add(matcher2.group());
			}else if(matcher3.find()){
				suggests.add(matcher3.group());
			}else{
				
			}
		}
		for (int i=0;i<symptomNames.size();i++) {
			MeridianAnalysis ma=new MeridianAnalysis(new Random().nextInt(9999999), hmstrId, symptomNames.get(i), symptoms.get(i), suggests.get(i));
			mas.add(ma);
		}
		return new ma(mas);
	}
	
	/**
	 * 解析检测报告
	 * @param document
	 * @return
	 */
	public static tr ParseTestReport(Document document,Long hmstrId){
		long trId=new Random().nextInt(9999999);
		TestReport testReport=new TestReport(trId,hmstrId);
		List<TrProblem> trProblems=new ArrayList<TrProblem>();
		List<MeridianChangeAnalysis> meridianChangeAnalysis=new ArrayList<MeridianChangeAnalysis>();
		Elements elements=document.select("table tbody");
		Element mca=null;
		Element trp=null;
		String mcastr=".*十二经络的变化分析.*";//正则表达式匹配十二经络的变化分析表头
		int i=0;
		//获取十二经络的变化分析表的信息
		for (Element element : elements) {
			Matcher matcher=Pattern.compile(mcastr).matcher(element.text());
			if (matcher.find()) {
				mca=elements.get(i+1);//获取十二经络的变化分析表节点
				trp=elements.get(i+3);//获取检测报告问题表节点
			}
			i++;
		}
		//将字符串转换为MeridianChangeAnalysis对象
		Elements elements2=mca.select("tr td");
		for(int j=3;j<elements2.size();){
			meridianChangeAnalysis.add(
			new MeridianChangeAnalysis(new Random().nextInt(9999999), trId, Integer.parseInt(elements2.get(j++).text()), elements2.get(j++).text(), elements2.get(j++).text())
			);
		}
		
		
		Elements elements3=trp.select("tr td");
		//将字符串转换为TrProblem对象
//		for(int l=3;l<elements3.size();l++) {
//			System.out.println("\""+elements3.get(l).text()+"\"");
//		}
		for(int k=3;k<elements3.size();){
			if(elements3.get(k).text().equals("◎倾向性或潜在性问题◎")){
				k++;
				for(;k<elements3.size();) {
					trProblems.add(
							new TrProblem(new Random().nextInt(9999999), elements3.get(k++).text(), elements3.get(k++).text(), "◎倾向性或潜在性问题◎", trId)
					);
				}
			}else{
				trProblems.add(
				new TrProblem(new Random().nextInt(9999999), elements3.get(k++).text(), elements3.get(k++).text(), "◎最可能的问题◎", trId)
				);
			}
		}
//		for (TrProblem trProblem:trProblems) {
//			System.out.println(trProblem.toString());
//		}

		return new tr(testReport,trProblems,meridianChangeAnalysis);
	}
	
	/**
	 * 解析经络表
	 * @param document
	 * @return
	 */
	public static mt ParseMeridianTable(Document document,Long hmstrId){
		long mtId=new Random().nextInt(9999999);
		MeridianTable meridianTable=new MeridianTable(mtId,hmstrId);
		List<MeridianData> meridianDatas=new ArrayList<MeridianData>();
		List<FiveJudgmentSystem> fiveJudgmentSystems=new ArrayList<FiveJudgmentSystem>();
		//解析获取五大判断系统表数据
		Elements fjs=document.select("body table").select("[class='table']").select("table tbody tr td").select("[class='td']");
		for(int i=4;i<fjs.size();){
			fiveJudgmentSystems.add(
			new FiveJudgmentSystem(new Random().nextInt(9999999), fjs.get(i++).text(), fjs.get(i++).text(), fjs.get(i++).text(), fjs.get(i++).text(), mtId)
			);
		}
		
		/**
		 * 用来解析经络数据的内部类
		 * @author dede
		 *
		 */
		class Parsemd{
			public List<String> parse(Elements md){
				//解析经络数据
				List<String> mdStrings=new ArrayList<String>();
				for(int i=0;i<md.size();i++){
					if(!(md.get(i).html().equals("&nbsp;"))){
						mdStrings.add(md.get(i).text());
						//解析经络状态
						if((i%6)!=0){
							switch (i%6) {
							case 1:
								mdStrings.add("低能量区（虚症）");
								break;
							case 2:
								mdStrings.add("较低能量区（较虚）");
								break;
							case 3:
								mdStrings.add("");
								break;
							case 4:
								mdStrings.add("较高能量区（较实）");
								break;
							case 5:
								mdStrings.add("高能量区（实症）");
								break;
							default:
								break;
							}
						}	
					}
				}
				for(int i=0;i<mdStrings.size();i++){
					String regex="(?<=[\u4e00-\u9fa5]=).*";
					Matcher matcher=Pattern.compile(regex).matcher(mdStrings.get(i));
					if(matcher.find()){
						mdStrings.set(i, matcher.group());
					}
				}
				return mdStrings;
			}
		}
		
		Elements mdright=document.select("body table tbody tr td").select("[background='Image/RightSide.jpg']").select("table tbody tr td");
		List<String> mdStringsRight=new Parsemd().parse(mdright);
		Elements mdleft=document.select("body table tbody tr td").select("[background='Image/LeftSide.jpg']").select("table tbody tr td");
		List<String> mdStringsLeft=new Parsemd().parse(mdleft);
		for(int j=0;j<mdStringsRight.size();){
			meridianDatas.add(
			new MeridianData(new Random().nextInt(9999999), mdStringsRight.get(j++),Float.parseFloat( mdStringsRight.get(j++)), mdStringsRight.get(j++),"右", mtId)
			);
		}
		for(int j=0;j<mdStringsLeft.size();){
			meridianDatas.add(
			new MeridianData(new Random().nextInt(9999999), mdStringsLeft.get(j++),Float.parseFloat( mdStringsLeft.get(j++)), mdStringsLeft.get(j++),"左", mtId)
			);
		}
		/*
		for (MeridianData meridianData : meridianDatas) {
			System.out.println(meridianData.toString());
		}*/
		
		return new mt(meridianTable,fiveJudgmentSystems,meridianDatas);
	}
	
	public static FiveElementsReport ParseFiveElementsReport(Document document,Long hmstrId){
		FiveElementsReport fer =new FiveElementsReport();
		Elements values=document.select("body table tbody tr td table tbody tr td table tbody tr td").select("[align='center']");
		Elements analysis=document.select("body table tbody tr td");
		
		//解析并设置value值
		int i=0;
		fer.setHepatobiliaryValue(Integer.parseInt(values.get(i++).text()));
		fer.setHeartIntestineValue(Integer.parseInt(values.get(i++).text()));
		fer.setSpleenStomachValue(Integer.parseInt(values.get(i++).text()));
		fer.setLungLargeIntestineValue(Integer.parseInt(values.get(i++).text()));
		fer.setKidneyBladderValue(Integer.parseInt(values.get(i++).text()));
		
		//解析并设置state值
		fer.setHepatobiliaryState(fer.getHepatobiliaryValue()>0?"旺":"衰");
		fer.setHeartIntestineState(fer.getHeartIntestineValue()>0?"旺":"衰");
		fer.setSpleenStomachState(fer.getSpleenStomachValue()>0?"旺":"衰");
		fer.setLungLargeIntestineState(fer.getLungLargeIntestineValue()>0?"旺":"衰");
		fer.setKidneyBladderState(fer.getKidneyBladderValue()>0?"旺":"衰");
		
		for(int j=0;j<analysis.size();j++){
			if(analysis.get(j).text().equals("分析")){
				fer.setHepatobiliaryAnalysis(analysis.get(++j).text());
				fer.setHeartIntestineAnalysis(analysis.get(++j).text());
				fer.setSpleenStomachAnalysis(analysis.get(++j).text());
				fer.setLungLargeIntestineAnalysis(analysis.get(++j).text());
				fer.setKidneyBladderAnalysis(analysis.get(++j).text());
			}else if(analysis.get(j).text().equals("表里关系")){
				fer.setRelationship(analysis.get(j+1).text());
			}else if(analysis.get(j).text().equals("养护理由")){
				fer.setMaintenanceReason(analysis.get(j+1).text());
			}else if(analysis.get(j).text().equals("养护之道")){
				fer.setWayOfCuring(analysis.get(j+1).text());
			}else{
				
			}
		}
		//System.out.println(fer.toString());
		fer.setHmstrId(hmstrId);
		return fer;
	}

	/**
	 * 解析柱状图
	 * @param document
	 * @param hmstrId
	 * @return
	 */
	public static Hisgtogram ParseHistogram(Document document,Long hmstrId){


		Elements utable=document.select("table.wtable").select("table.utable");
		/**
		 * 定义values保存柱状图中上半部分数据
		 * 定义values1保存柱状图中下半部分数据
		 * 定义len为values数组下标
		 * 定义len1为values1数组下标
		 */
		int[] values=new int[24];
		int[] values1=new int[24];
		int len=0;
		int len1=0;
		for (Element e:utable) {
			int leftValue=0;
			int rightValue=0;
			Elements elements2=e.select("tbody tr td table tbody");
			if(!elements2.get(1).text().equals("")){//获取左边数据，若为空，设值为0
				leftValue=Integer.valueOf(elements2.get(1).text());
			}else{
				leftValue=0;
			}
			if(!elements2.get(3).text().equals("")){//获取右边数据，若为空，设值为0
				rightValue=Integer.valueOf(elements2.get(3).text()) ;
			}else{
				rightValue=0;
			}
			values[len++]=leftValue;
			values[len++]=rightValue;
		}
		Elements ultable=document.select("table.wtable").select("table.ultable").select("tbody tr td table tbody");
		values[len++]=ultable.get(1).text().equals("")?0:Integer.valueOf(ultable.get(1).text());
		values[len++]=ultable.get(3).text().equals("")?0:Integer.valueOf(ultable.get(3).text());

		Elements dtable=document.select("table.xtable").select("table.dtable");
		for (Element d:dtable) {
			int leftValue1=0;
			int rightValue1=0;
			Elements elements2=d.select("tbody tr td table tbody");
			if(!elements2.get(1).text().equals("")){//获取左边数据，若为空，设值为0
				String string1 =elements2.get(1).text().split(" ")[0];
				leftValue1=Integer.valueOf(string1);
			}else{
				leftValue1=0;
			}//左边的值为负
			if(!elements2.get(3).text().equals("")){//获取右边数据，若为空，设值为0
				rightValue1=Integer.valueOf(elements2.get(3).text().split(" ")[0]);
			}else{
				rightValue1=0;
			}
			values1[len1++]=leftValue1;
			values1[len1++]=rightValue1;
		}
		//获取表最右边的数值
		Elements ultable2=document.select("table.xtable").select("table.ultable").select("tbody tr td table tbody");
		values1[len1++]=ultable2.get(1).text().equals("")?0:Integer.valueOf(ultable2.get(1).text().split(" ")[0]);
		values1[len1++]=ultable2.get(3).text().equals("")?0:Integer.valueOf(ultable2.get(3).text().split(" ")[0]);
		int i=0;
		//按顺序依次将值存入对象，若values[i]当前值为0则在values1[i]中取值
		Hisgtogram hisgtogram=new Hisgtogram(values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++]
				,values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++]
				,values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++]
				,values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++]
				,values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++]
				,values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++]
				,values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++]
				,values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++],values[i]==0?values1[i++]:values[i++]
				,values[i]==0?values1[i++]:values[i++]);
		hisgtogram.setUid(new Random().nextInt(9999999));
		hisgtogram.setHtg_id(hmstrId.intValue());

		System.out.print(hisgtogram.toString());
		return hisgtogram;
	}
	public static void main(String[] args){
		HmstrParseUtil hmstrParseUtil =new HmstrParseUtil();
		hmstrParseUtil.ParseTestReport(hmstrParseUtil.ReadFile("C:/Users/dede/Desktop/经络报告/新建文件夹/13602896904(检测报告).htm"),0L);

		/*
		for (MeridianAnalysis meridianAnalysis : mas) {
			System.out.println(meridianAnalysis);
		}
		*/
	}

}
